<template>
	<view :style="themeColor()">
		<u-icon name="arrow-left" class="navigate-back" @click="navigateBack"></u-icon>
		<!-- <web-view src="/hybrid/html/index.html" class="mt-60rpx" @message="getMessage"></web-view> -->
		<web-view :src="src" class="mt-60rpx" @message="getMessage"></web-view>

	</view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { computed, ref } from 'vue';
import { redirect } from '@/utils/common';
import { createMemberBaby, updateMemberBaby } from '../api';

const src = ref('https://fmobile.meton.vip/') //对应 hybrid/html/index.html
// const src = ref('/hybrid/html/index.html') //对应 hybrid/html/index.html

const operationType = ref('add') //
const bpmId = ref('') //模板id
const type = ref('1') //模板类型
const memberId = ref(undefined) //对应的提交的表单id
const formJson = ref({}) //自定义的表单模版

onLoad((option: any) => {
	operationType.value = option.type
	let config = option.type == 'add' ? uni.getStorageSync('addMember') : uni.getStorageSync('memberInfo')
	if (option.type == 'add') {
		bpmId.value = config.id;
		type.value = config.type
		memberId.value = undefined
	} else {
		bpmId.value = config.bpmId;
		type.value = config.type
		memberId.value = config.id
	}


	formJson.value = JSON.stringify({
		conf: config.conf,
		fields: config.fields
	});
	src.value = src.value + `?id=${bpmId.value}&type=${type.value}&memberId=${memberId.value}&formJson=${formJson.value}`;

})

const getMessage = (e: any) => {
	console.log(e)
	// #ifdef MP-WEIXIN
	if (e.target.data[1]) {
		sumbit(e.target.data[1].formData)
	}
	// #endif



};

// #ifdef H5
window.addEventListener('message', (e) => {
	if (e.data.data.arg.action == 'sumbit') {
		sumbit(e.data.data.arg.formData)
	}
});
// #endif
let wap_member_id = uni.getStorageSync('wap_member_id');

const sumbit = (params: any) => {
	const api = params.memberId == 'undefined' ? createMemberBaby : updateMemberBaby
	let paramsData = {
		userId: wap_member_id,
		bpmId: params.id,
		id: params.memberId == 'undefined' ? undefined : Number(params.memberId),
		conf: params.conf,
		fields: params.fields
	}
	api(paramsData).then((res: any) => {
		if (res.code == 0) {
			uni.showToast({
				title: params.memberId == 'undefined' ? '创建档案成功' : '修改档案成功',
				icon: 'none'
			})
		}
		// #ifdef H5
		redirect({ url: `/addon/ertui/pages/member-profile`, param: { type: 'add' }, mode: 'redirectTo' })
		// #endif

	})

}
const navigateBack = () => {
	if (getCurrentPages().length > 1) {
		uni.navigateBack({
			delta: 1
		});
	} else {
		redirect({
			url: '/app/pages/index/index',
			mode: 'reLaunch'
		});
	}
}
</script>

<style lang="scss" scoped>
.navigate-back {
	position: absolute;
	top: 34rpx;
	left: 34rpx;
	z-index: 999;
	font-size: 16px;
}
</style>